package control;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class ConnectionManage
{
	private static ConnectionManage instance = null;
    private String DBNAME = "vcp";
	private String USERNAME = "root"; //default
	private String PASSWORD = "";     // default
	private String host = "localhost"; // default 
	private String port = "3306";      // default
	private static String driver = "com.mysql.jdbc.Driver"; // default
	
	//private static final String M_CONN_STRING =
	//		"jdbc:mysql://localhost/vcp?zeroDateTimeBehavior=convertToNull";
    
	private String connStr;
	
	


	private Connection conn = null;
	

	private ConnectionManage() {
		
	}
    
	
	/**
	 * Make sure MYSQL set up for TCP/IP then return instance
	 * @return connection
	 */
	public static ConnectionManage getInstance() {
		if (instance == null) {
			 try {		           
		            Class.forName(driver).newInstance();
		        } catch (Exception ex) {
		            ex.printStackTrace();
		        }
			instance = new ConnectionManage();
		}
		return instance;
	}

	

	private boolean openConnection()
	{
		try {
			conn = DriverManager.getConnection(getMysqlConnStr(), getUSERNAME(), getPASSWORD());
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public Connection getConnection()
	{
		if (conn == null) {
			if (openConnection()) {
				System.out.println("Connection opened");
				return conn;
			} else {
				return null;
			}
		}
		return conn;
	}

	public void close() {
		System.out.println("Closing connection");
		try {
			conn.close();
			conn = null;
		} catch (Exception e) {
		}
	}
	
	
	
	public String getUSERNAME() {
		return USERNAME;
	}


	public void setUSERNAME(String uSERNAME) {
		USERNAME = uSERNAME;
	}


	public String getPASSWORD() {
		return PASSWORD;
	}


	public void setPASSWORD(String pASSWORD) {
		PASSWORD = pASSWORD;
	}


	public String getMysqlConnStr() {
		String host = getHost();
		String port = getPort();
		String dbname = getDBNAME();
		String connStr = null;
		if(!host.isEmpty() && !port.isEmpty() && !dbname.isEmpty()){
			connStr = "jdbc:mysql://"+host+":"+
		                                     port+
		                                     "/"+dbname+"?zeroDateTimeBehavior=convertToNull";
		}
		return connStr;
	}
	
	
	public String getHost() {
		return host;
	}


	public void setHost(String host) {
		this.host = host;
	}


	public String getPort() {
		return port;
	}


	public void setPort(String port) {
		this.port = port;
	}


	public String getDBNAME() {
		return DBNAME;
	}


	public void setDBNAME(String dBNAME) {
		DBNAME = dBNAME;
	}


	

}